import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import com.bulenkov.darcula.DarculaLaf;

/**
 * Created by LLAP on 2017/12/4.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class Server extends JFrame {
    private ArrayList<UserQueue> queueList = new ArrayList<>();
    private ServerThread serverThread;
    private BroadcastThread broadcastThread;
    private int requestPort = 1926;
    private Logger logger;
    private JTable queueTable;
    private StatusBar statusBar;
    private ActionBar actionBar;
    private QueueTableModel queueTableModel;

    public Server() {
        super("Server");
        this.setSize(600, 600);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(getOwner());
        this.setLayout(new BorderLayout());
        try {
            UIManager.setLookAndFeel(new DarculaLaf());
        } catch (Exception e) {
            try {
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            }
            catch (Exception ex) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                }
                catch (Exception exc) {
                    System.out.println("Substance Raven Graphite failed to initialize");
                }
            }
        }
        logger = new Logger("Server");
        queueTableModel = getModel();
        queueTable = new JTable(queueTableModel);
        queueTable.setFont(new Font("Microsoft Yahei UI", 0, 14));
        queueTable.setRowHeight(18);
        this.add(new JScrollPane(queueTable), BorderLayout.CENTER);

        actionBar = new ActionBar();
        actionBar.addButton("新建队列");
        actionBar.addButton("删除队列");
        actionBar.save();
        this.add(actionBar, BorderLayout.NORTH);

        statusBar = new StatusBar();
        statusBar.addText(" ");
        this.add(statusBar, BorderLayout.SOUTH);

        actionBar.getButton(0).addActionListener((e) -> {
            logger.log("新建队列" + (char)('A' + queueList.size()));
            queueList.add(new UserQueue(queueList.size(), "队列" + (char)('A' + queueList.size())));
            updateTable();
        });

        actionBar.getButton(1).addActionListener((e) -> {
            try {
                queueList.remove(queueList.size() - 1);
                logger.log("移除队列" + (char)('A' + queueList.size()));
                updateTable();
            }
            catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        });

        TableCellEditor editor = queueTable.getDefaultEditor(JTable.class);
        editor.addCellEditorListener(new CellEditorListener() {
            @Override
            public void editingStopped(ChangeEvent e) {
                if (queueTable.getCellEditor() != null) queueTable.getCellEditor().stopCellEditing();
                try {
                    int count = queueTableModel.getEditedIndex().size();
                    if (count > 0) {
                        for (int i = 0; i < count; i++) {

                            int index = queueTableModel.getEditedIndex().get(i);
//                            System.out.println(index);
//                            System.out.println(queueTable.getValueAt(index, 2).toString());
//                            System.out.println(queueList.get(index).getQueueName());
                            queueList.get(index).setComment(queueTable.getValueAt(index, 2).toString());
                            queueList.get(index).setGroup(queueTable.getValueAt(index, 4).toString());
                            logger.log("队列" + (char)('A' + index) + "改名为" + queueTable.getValueAt(index, 2).toString());
                            logger.log("队列" + (char)('A' + index) + "分组改为" + queueTable.getValueAt(index, 4).toString());
                        }
                        updateTable();
                    }
                }
                catch (Exception ex) {}
            }

            @Override
            public void editingCanceled(ChangeEvent e) {

            }
        });
        broadcastThread = new BroadcastThread(queueList, 1000);
        broadcastThread.start();

        serverThread = new ServerThread(queueList, this);
        serverThread.start();
    }

    public synchronized void updateTable() {
        queueTableModel = getModel();
        queueTable.setModel(queueTableModel);
        queueTable.updateUI();
        int waitCount = 0;
        for (UserQueue i : queueList) {
            waitCount += i.getSize();
        }
        statusBar.getText(0).setText(String.format("队列数：%d   排队人数：%d", queueList.size(), waitCount));
        statusBar.updateUI();
        // 队列数：x  排队人数：x
    }

    private QueueTableModel getModel() {
        QueueTableModel t = new QueueTableModel();
        // 序号 队列项目（ABCD） 队列名称 队列人数
        t.addColumn("序号");
        t.addColumn("队列编号");
        t.addColumn("队列名称");
        t.addColumn("等待人数");
        t.addColumn("队列分组");
        for (int i = 0; i < queueList.size(); i++) {
            t.addRow(new String[] {
                    String.valueOf(i),
                    queueList.get(i).getQueueName() + "",
                    queueList.get(i).getComment(),
                    String.valueOf(queueList.get(i).getSize()),
                    queueList.get(i).getGroup()
            });
        }
        return t;
    }

    public static void main(String[] args) {
        new Server().setVisible(true);
    }
}
class StatusBar extends JToolBar {
    ArrayList<JLabel> labels = new ArrayList<>();

    public StatusBar() {
        super();
        this.setFloatable(false);
        this.setBorder(new EmptyBorder(5, 5, 5, 5));
    }

    public void addText(String s) {
        JLabel b = new JLabel(s);
        labels.add(b);
        this.add(b);
    }

    public JLabel getText(int i) {
        return labels.get(i);
    }
}
class ActionBar extends JPanel {
    ArrayList<JButton> buttons = new ArrayList<>();

    public ActionBar() {
        super();
    }

    public void addButton(String s) {
        JButton b = new JButton(s);
        b.setFocusable(false);
        b.setHorizontalTextPosition(SwingConstants.CENTER);
        b.setVerticalTextPosition(SwingConstants.CENTER);
        buttons.add(b);
    }

    public void save(int gap) {
        this.setLayout(new GridLayout(1, buttons.size(), gap, gap));
        for (JButton i : buttons) {
            this.add(i);
        }
    }

    public void save() {this.save(0);}

    public JButton getButton(int i) {
        return buttons.get(i);
    }
}